package com.qs.service.impl;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.mapper.MenuMapper;
import com.qs.mapper.entity.Form;
import com.qs.mapper.entity.Menu;
import com.qs.service.FormService;
import com.qs.service.MenuService;
import com.qs.service.bo.MenuBO;
import com.qs.util.BeanCopyUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service("menuService")
@RequiredArgsConstructor
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    private final FormService formService;
    private final StpInterface stpInterface;

    @Override
    public List<MenuBO> getMenuList() {
        List<Menu> menuList = list();
        List<MenuBO> menuBOList = BeanCopyUtils.copyBeanList(menuList, MenuBO.class);
        List<Form> dataTableList = formService.list();
        for (Form form : dataTableList) {
            MenuBO menuBO = BeanCopyUtils.copyBean(form, MenuBO.class);
            menuBO.setId(1L - menuBOList.size());
            menuBO.setPid(1L);
            menuBO.setPath("/" + form.getName());
            menuBO.setComponent("@/pages/table");
            menuBO.setPermissions(form.getRole());
            menuBOList.add(menuBO);
        }
//        List<String> permissionList = stpInterface.getPermissionList(StpUtil.getLoginId(), StpUtil.getLoginType());
        // 以角色作为权限
        List<String> permissionList = stpInterface.getRoleList(StpUtil.getLoginId(), StpUtil.getLoginType());
        menuBOList = menuBOList.stream()
                .peek(menuBO -> {
                    menuBO.setCacheable(false);
                    menuBO.setRenderMenu(true);
                })
                .filter(menuBO -> StpUtil.getLoginId().equals("admin") || permissionList.contains(menuBO.getPermissions()) || !StringUtils.hasText(menuBO.getPermissions()))
                .toList();
        menuBOList = listToTree(menuBOList, 0L);
        menuBOList.sort(Comparator.comparing(MenuBO::getId).reversed());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return menuBOList;
    }

    private List<MenuBO> listToTree(List<MenuBO> list, Long pid) {
        return list.stream()
                // 过滤父节点
                .filter(parent -> parent.getPid().equals(pid))
                // 把父节点children递归赋值成为子节点
                .peek(child -> child.setChildren(listToTree(list, child.getId()))).collect(Collectors.toList());
    }
}
